package org.budo.storm.jdbc.connection;

import java.sql.Connection;

import org.apache.storm.jdbc.common.ConnectionProvider;
import org.budo.storm.trident.operation.RuntimeFilterReference;
import org.budo.support.spring.context.aware.BudoApplicationContextAware;
import org.budo.support.spring.util.SpringUtil;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class RuntimeConnectionProviderReference implements ConnectionProvider {
    private static final long serialVersionUID = -946762633147017069L;

    private String beanName;

    private String configLocation;

    private ConnectionProvider getConnectionProvider() {
        if (null != BudoApplicationContextAware.getInstance()) {
            return (ConnectionProvider) SpringUtil.getBean(this.getBeanName());
        }

        synchronized (RuntimeFilterReference.class) {
            if (null != BudoApplicationContextAware.getInstance()) {
                return (ConnectionProvider) SpringUtil.getBean(this.getBeanName());
            }

            new ClassPathXmlApplicationContext(this.getConfigLocation());
            return (ConnectionProvider) SpringUtil.getBean(this.getBeanName());
        }
    }

    @Override
    public void prepare() {
        this.getConnectionProvider().prepare();
    }

    @Override
    public Connection getConnection() {
        return this.getConnectionProvider().getConnection();
    }

    @Override
    public void cleanup() {
        this.getConnectionProvider().cleanup();
    }
}